/**
 * 认证相关组合式函数
 */
import { ref, computed, watch } from "vue";
import { useRouter } from "vue-router";
import { useUserStore } from "@/stores/user";
import { ElMessage } from "element-plus";
import type { LoginRequest, RegisterRequest } from "@/types/user";

export function useAuth() {
  const router = useRouter();
  const userStore = useUserStore();

  const loading = ref(false);
  const loginForm = ref<LoginRequest>({
    username: "",
    password: "",
    remember: false,
  });

  const registerForm = ref<RegisterRequest>({
    username: "",
    email: "",
    password: "",
    confirmPassword: "",
    verificationCode: "",
  });

  // 计算属性
  const isAuthenticated = computed(() => userStore.isAuthenticated);
  const currentUser = computed(() => userStore.user);

  // 登录
  const login = async (credentials?: LoginRequest) => {
    loading.value = true;

    try {
      const loginData = credentials || loginForm.value;

      await userStore.login(loginData);

      ElMessage.success("登录成功");

      // 跳转到首页或之前的页面
      const redirect = router.currentRoute.value.query.redirect as string;
      await router.push(redirect || "/");

      return true;
    } catch (error: any) {
      ElMessage.error(error.message || "登录失败");
      return false;
    } finally {
      loading.value = false;
    }
  };

  // 注册
  const register = async (userData?: RegisterRequest) => {
    loading.value = true;

    const registerData = userData || registerForm.value;

    // 验证密码确认
    if (registerData.password !== registerData.confirmPassword) {
      ElMessage.error("两次输入的密码不一致");
      loading.value = false;
      return false;
    }

    try {
      await userStore.register(registerData);

      ElMessage.success("注册成功，请登录");
      await router.push("/login");

      return true;
    } catch (error: any) {
      ElMessage.error(error.message || "注册失败");
      return false;
    } finally {
      loading.value = false;
    }
  };

  // 登出
  const logout = async () => {
    loading.value = true;

    try {
      await userStore.logout();

      ElMessage.success("已退出登录");
      await router.push("/login");

      return true;
    } catch (error: any) {
      ElMessage.error(error.message || "退出登录失败");
      return false;
    } finally {
      loading.value = false;
    }
  };

  // 刷新令牌
  const refreshToken = async () => {
    try {
      await userStore.refreshToken();
      return true;
    } catch {
      // 刷新失败，跳转到登录页
      await logout();
      return false;
    }
  };

  // 检查认证状态
  const checkAuth = async () => {
    if (!userStore.token) {
      return false;
    }

    try {
      // 验证令牌有效性
      const isValid = await userStore.validateToken();
      if (!isValid) {
        await logout();
        return false;
      }

      return true;
    } catch {
      // 验证失败，登出并返回false
      await logout();
      return false;
    }
  };

  // 重置表单
  const resetLoginForm = () => {
    loginForm.value = {
      username: "",
      password: "",
      remember: false,
    };
  };

  const resetRegisterForm = () => {
    registerForm.value = {
      username: "",
      email: "",
      password: "",
      confirmPassword: "",
      verificationCode: "",
    };
  };

  // 监听认证状态变化
  watch(
    () => userStore.isAuthenticated,
    (newValue) => {
      if (!newValue && router.currentRoute.value.meta.requiresAuth) {
        router.push({
          path: "/login",
          query: { redirect: router.currentRoute.value.fullPath },
        });
      }
    },
  );

  return {
    // 状态
    loading,
    loginForm,
    registerForm,
    isAuthenticated,
    currentUser,

    // 方法
    login,
    register,
    logout,
    refreshToken,
    checkAuth,
    resetLoginForm,
    resetRegisterForm,
  };
}
